package com.ruoyi.common.aliyun;
import java.math.BigDecimal;

import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

/**
 * 	支付宝提现
 * @author DEREK
 *
 */
@Component
public class AliPaymentConfig {

	@Resource
	private AlipayClient alipayClient;

	@Value("${alipay.config.appId}")
	private String appId;
	@Value("${alipay.config.appPrivateKey}")
	private String appPrivateKey;
	@Value("${alipay.config.alipayPublicKey}")
	private String appCrePublicKey;

	@Value("${alipay.config.publicCertPath}")
	private String publicCertPath;
	
	@Value("${alipay.config.publicCertRAS2Path}")
	private String publicCertRAS2Path;
	
	@Value("${alipay.config.RootCertPath}")
	private String rootCertPath;
	
	
//	private static final String ROOT_URL = "/usr/local/alipay/";

	static String RESULT_JSON_STATUS = "status";
	static String RESULT_JSON_MSG = "msg";

	/**
	 * 	支付宝原路退款
	 * @param tradeNo
	 * @param amount
	 * @return
	 */
	public String aliPayOriginalRefund(String tradeNo,BigDecimal amount,String refundReason) {
		String retStr = "SUCCESS";
		try {
			//构造client
			CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();

			//设置网关地址
			certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
			//设置应用Id
			certAlipayRequest.setAppId(appId);
			//设置应用私钥
			certAlipayRequest.setPrivateKey(appPrivateKey);
			//设置请求格式，固定值json
			certAlipayRequest.setFormat("json");	
			//设置字符集
			certAlipayRequest.setCharset("UTF-8");
			//设置签名类型
			certAlipayRequest.setSignType("RSA2");
			//设置应用公钥证书路径
			certAlipayRequest.setCertPath(publicCertPath);
			//设置支付宝公钥证书路径
			certAlipayRequest.setAlipayPublicCertPath(publicCertRAS2Path);
			//设置支付宝根证书路径
			certAlipayRequest.setRootCertPath(rootCertPath);
			//构造client
			AlipayClient alipayClient = null;
			try {
				alipayClient = new DefaultAlipayClient(certAlipayRequest);
			} catch (AlipayApiException e1) {
				e1.printStackTrace();
			}
			AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
			JSONObject bizContent = new JSONObject();
			bizContent.put("trade_no", tradeNo);
			bizContent.put("refund_amount", amount);
			bizContent.put("refund_reason", "必达咨询-"+refundReason);
			request.setBizContent(bizContent.toString());
			AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
			System.out.println(response.getBody());
			if(!response.isSuccess()){
				JSONObject parseObject = JSONObject.parseObject(response.getBody());
				retStr = parseObject.getString("code")+","+parseObject.getString("msg")+","+parseObject.getString("sub_code");
			}
		} catch (Exception e) {
			retStr = e.getMessage();
		}
		return retStr;
		
		
	}
	
	
	
	public static void main(String[] args) throws AlipayApiException {
		//构造client
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();

		//设置网关地址
		certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
		//设置应用Id
		certAlipayRequest.setAppId("2021004132648330");
		//设置应用私钥
		certAlipayRequest.setPrivateKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCbmSxVWcbGzyk5K27wZo1KOMVp5DtQh02OkBxw0Izd2LTvIS1H+8HzNG/cXJJwZARS+Re965W6pc41OOTGkTAZkfqvffjDEWYgDEI8+7VSjj9gYfRhGXjErQXEp9x+lpwOoAvcjWQEljvjO/6C7JSMN/7GBEvfjbnTXvBot8EU7qaQdbHWC8TK8h6DnuOcLAUxMTLUYyNy3xPAI1QjInU6DN+jCDlOTxDPcN9Q+1m5j4layjEsUnxIsYIieEV4xk85iNi/NITS95Jfdq3WpqT0SAyl37rcui3ci77ws+D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+yHjjIr+qTivyDHUgQKBgEByixd6s5PZwpaqaWMeEh8pJXyjwPYHynlVnMfQ5HDGPNrLc4YliajoS2PMTwLiiM0qWDOE0t/DS0hazCJi3BGrSb2j9PxYcy29gRMp4q0pC0TeLn8DTkV9ZfIiq/pefRT7OXZPT/V6UetFEpdNxFhd/c8kdX+yCTBFl5fCtt+l");
		//设置请求格式，固定值json
		certAlipayRequest.setFormat("json");	
		//设置字符集
		certAlipayRequest.setCharset("UTF-8");
		//设置签名类型
		certAlipayRequest.setSignType("RSA2");
		//设置应用公钥证书路径
		certAlipayRequest.setCertPath("/www/wwwroot/alipay/appCertPublicKey.crt");
		//设置支付宝公钥证书路径
		certAlipayRequest.setAlipayPublicCertPath("/www/wwwroot/alipay/alipayCertPublicKey_RSA2.crt");
		//设置支付宝根证书路径
		certAlipayRequest.setRootCertPath("/www/wwwroot/alipay/alipayRootCert.crt");
		//构造client
		AlipayClient alipayClient = null;
		try {
			alipayClient = new DefaultAlipayClient(certAlipayRequest);
		} catch (AlipayApiException e1) {
			e1.printStackTrace();
		}
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		JSONObject bizContent = new JSONObject();
		bizContent.put("trade_no", "2023101822001457511404596990");
		bizContent.put("refund_amount", 0.1);
		bizContent.put("refund_reason", "必达咨询-打赏咨询师退款");
		
		//// 返回参数选项，按需传入
		//JSONArray queryOptions = new JSONArray();
		//queryOptions.add("refund_detail_item_list");
		//bizContent.put("query_options", queryOptions);
		request.setBizContent(bizContent.toString());
		AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
		System.out.println(response);
		System.out.println(response.getBody());
		if(response.isSuccess()){
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}
	}



	/**
	 * 	提现接口
	 * @param orderNo
	 * @param alipayPayAccount
	 * @param amount
	 * @param realName
	 * @return
	 * @throws AlipayApiException
	 */
	public JSONObject aliPayToUser(String orderNo, String alipayPayAccount, String amount,String realName) throws AlipayApiException {
		JSONObject resultJson = new JSONObject();
		resultJson.put(RESULT_JSON_STATUS ,0);
		resultJson.put(RESULT_JSON_MSG , "提现异常");
		// 初始化
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
		// 支付宝网关
		certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
		certAlipayRequest.setAppId(appId);
		certAlipayRequest.setPrivateKey(appPrivateKey);
		certAlipayRequest.setCertPath(publicCertPath);
		certAlipayRequest.setAlipayPublicCertPath(publicCertRAS2Path);
		certAlipayRequest.setRootCertPath(rootCertPath);
//		certAlipayRequest.setCertPath("D:\\cer\\appCertPublicKey.crt");
//		//设置支付宝公钥证书路径
//		certAlipayRequest.setAlipayPublicCertPath("D:\\cer\\alipayCertPublicKey_RSA2.crt");
//		//设置支付宝根证书路径
//		certAlipayRequest.setRootCertPath("D:\\cer\\alipayRootCert.crt");
		certAlipayRequest.setSignType("RSA2");
		certAlipayRequest.setFormat("json");
		certAlipayRequest.setCharset("UTF-8");
		AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
		AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
		AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
		model.setOutBizNo(orderNo);
		model.setTransAmount(amount);
		model.setProductCode("TRANS_ACCOUNT_NO_PWD");
		model.setBizScene("DIRECT_TRANSFER");
		model.setOrderTitle("蜜搭");
		Participant participant = new Participant();
		participant.setIdentityType("ALIPAY_LOGON_ID");//ALIPAY_USER_ID
		participant.setIdentity(alipayPayAccount);
		participant.setName(realName);
		model.setPayeeInfo(participant);
		request.setBizModel(model);
		AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
		if (response.isSuccess() && response.getCode().equals("10000")) {
			//保存用户账单信息
			resultJson.put(RESULT_JSON_STATUS ,1);
			resultJson.put(RESULT_JSON_MSG , "提现成功");
		}else{
			resultJson.put(RESULT_JSON_STATUS ,0);
			resultJson.put(RESULT_JSON_MSG , response.getSubMsg());
		}
		return resultJson;
	}
}
